package com.newtouch.paas.shell;

import com.jcraft.jsch.*;
import com.newtouch.lion.common.Assert;
import com.newtouch.paas.shell.userinfo.ShellCommand;
import com.newtouch.paas.shell.userinfo.ShellUserInfo;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by wanglijun on 16/5/17.
 */
public class ShellCommandExecutor {




    /**日志*/
    private static final Logger logger= LoggerFactory.getLogger(ShellCommandExecutor.class);

    public static final String CHANNEL_TYPE_EXEC="exec";


    private static  JSch jsch=new JSch();


    public ShellCommand execute(ShellCommand  shellCommand){

        //Create session
        Session session=this.getSession(shellCommand.getShellUserInfo());
        Channel channel=null;
        BufferedReader input=null;
        Assert.notNull(session);
        try {
            //connect session
            session.connect();

             channel=session.openChannel(CHANNEL_TYPE_EXEC);
            //设置命令
            (( ChannelExec)channel).setCommand(shellCommand.getCommand());

            channel.setInputStream(null);
            input= new BufferedReader(new InputStreamReader(channel.getInputStream()));

            channel.connect();
            logger.info("The remote command is: {}" ,shellCommand.getCommand());

            // Get the output of remote command.
            StringBuilder sb=new StringBuilder();
            String line=null;
            while ((line = input.readLine()) != null) {
                sb.append(line);
            }

            // Get the return code only after the channel is closed.
            if (channel.isClosed()) {
                shellCommand.setReturnCode(channel.getExitStatus());
            }

        } catch (JSchException e) {
            throw new ShellException("SSH_002",e.getMessage(),e);
        } catch (IOException e){
            throw new ShellException("SHH_003",e.getMessage(),e);
        }finally{
            if (input != null) {
                IOUtils.closeQuietly(input);
            }
            session.disconnect();
            if(channel!=null){
                channel.disconnect();
            }
        }

        return shellCommand;
    }


    private Session getSession(ShellUserInfo shellUserInfo){
        Session session=null;
        try {
             session=jsch.getSession(shellUserInfo.getUsername(),shellUserInfo.getHost(),shellUserInfo.getPort());
             session.setPassword(shellUserInfo.getPassword());
             session.setUserInfo(shellUserInfo);


        } catch (JSchException e) {
             throw new ShellException("SSH_001",e.getMessage(),e);
        }
        return session;
    }
}
